/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-09-08
 * Time: 15:20
 */
public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] arr = new Node[10];
    public static final double DEFAULT_LOAD_FACTOR = 0.75f;
    public int userSize;

    //插入数据_尾插
    public void putEnd(int key,int val) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        Node node = new Node(key,val);
        if (arr[index] == null) {
            arr[index] = node;
        }else {
            cur = arr[index];
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
        }
        userSize++;
        //判断是否需要扩容
        if (doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            reSize();
        }
    }

    private double doLoadFactor() {
        return userSize*1.0/arr.length;
    }

    private void reSize() {
        Node[] newArr = new Node[2*arr.length];
        for (int i = 0; i < arr.length; i++) {
            Node cur = arr[i];
            while (cur != null) {
                int newIndex = cur.key % newArr.length;
                Node curN = cur.next;
                if (newArr[newIndex] == null) {
                    newArr[newIndex] = cur;
                    cur.next = null;
                }else {
                    Node prev = newArr[newIndex];
                    while (prev.next != null) {
                        prev = prev.next;
                    }
                    prev.next = cur;
                    cur.next = null;
                }
                cur = curN;
            }
        }
        arr = newArr;
    }

    //查找
    public int getVal(int key) {
        int index = key % arr.length;
        Node cur = arr[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        //找不到返回-1
        return -1;
    }
}
